﻿//准备ExtJS环境
Ext.require
(
    [
        'Ext.grid.*',
        'Ext.data.*',
        'Ext.util.*',
        'Ext.state.*',
        'Ext.form.*'
    ]
);

//用于保存字典编号
var current_dictionay_id;

//定义用户表格控件
Ext.define
(
    'DictionayItem.Grid',
    {
    	extend: 'Ext.grid.Panel',

    	//检索窗体
    	win_search: null,

    	//编辑窗体
    	win_edit: null,

    	//新增窗体
    	win_create: null,

    	//初始化组件
    	initComponent: function ()
    	{
    		Ext.apply
            (
                this,
                {
                	listeners:
                    {
                    	//设置两个指头的滚动
                    	render: Common.ScrollableRender
                    },
                	dockedItems:
                    [
                        {
                        	xtype: 'toolbar',
                        	height: 36,
                        	items:
                            [
                                {
                                	iconCls: 'icon-refresh',
                                	text: '刷新',
                                	scope: this,
                                	hidden: false,
                                	tooltip: '刷新数据',
                                	handler: this.onRefreshClick
                                },
                                '-',
                                {
                                	iconCls: 'icon-add',
                                	itemId: 'dictionayitem-add',
                                	text: '新增',
                                	scope: this,
                                	hidden: false,
                                	disabled: false,
                                	tooltip: '新增条目',
                                	handler: this.onAddClick
                                },
                                {
                                	iconCls: 'icon-delete',
                                	text: '删除',
                                	disabled: true,
                                	hidden: false,
                                	itemId: 'dictionayitem-delete',
                                	scope: this,
                                	tooltip: '删除条目',
                                	handler: this.onDeleteClick
                                },
                                {
                                	iconCls: 'icon-edit',
                                	text: '编辑',
                                	itemId: 'dictionayitem-edit',
                                	disabled: true,
                                	hidden: false,
                                	scope: this,
                                	tooltip: '编辑条目',
                                	handler: this.onEditClick
                                },
                                '->',
                                '字典分类：',
                                {
                                	xtype: 'combobox',
                                	editable: false,
                                	width: 240,
                                	name: 'unit',
                                	itemId: 'dictionayitem_category',
                                	store: store_master_categories,
                                	displayField: 'Name',
                                	valueField: 'ID',
                                	queryMode: 'local',
                                	hideTrigger: false,
                                	listeners:
                                    {
                                    	change: function (field, newValue, oldValue, options)
                                    	{
                                    		//保存字典编号
                                    		current_dictionay_id = newValue;

                                    		//获得存储对象
                                    		var store = Ext.getCmp('dictionayitem-grid').store;

                                    		//清除过滤条件
                                    		store.filters.clear();

                                    		//过滤数据
                                    		store.filter
                                            (
                                                [
                                                    {
                                                    	property: 'DictionayID',
                                                    	value: current_dictionay_id
                                                    }
                                                ]
                                            );
                                    	}
                                    }
                                }
                            ]
                        }
                    ]
                }
            );
    		this.callParent();
    		this.getSelectionModel().on('selectionchange', this.onSelectionChange, this);
    	},

    	//处理选中条目变化事件
    	onSelectionChange: function (selectionModel, selections)
    	{
    		//判断是否选中条目
    		if (selections.length === 0)
    		{
    			//禁用删除按钮
    			this.down('#dictionayitem-delete').setDisabled(true);
    			//禁用编辑按钮
    			this.down('#dictionayitem-edit').setDisabled(true);
    		}
    		else
    		{
    			//获得选中的行
    			var selection = this.getView().getSelectionModel().getSelection()[0];

    			//启用删除按钮
    			this.down('#dictionayitem-delete').setDisabled(selection.data.IsBuildin);
    			//启用编辑按钮
    			this.down('#dictionayitem-edit').setDisabled(false);
    		}
    	},

    	//处理删除按钮点击事件
    	onDeleteClick: function ()
    	{
    		//获得数据存储对象
    		var store = this.store;

    		//获得选中的行
    		var selection = this.getView().getSelectionModel().getSelection()[0];

    		//判断是否选中行
    		if (selection)
    		{
    			//询问是否确定删除
    			Ext.Msg.show
                (
                    {
                    	title: '删除条目',
                    	width: 320,
                    	height: 240,
                    	msg: '确定要删除选中的条目"' + selection.data.ItemName + '"吗?',
                    	buttons: Ext.Msg.YESNO,
                    	icon: Ext.Msg.QUESTION,
                    	fn: function (button)
                    	{
                    		//判断是否确定删除 
                    		if (button == 'yes')
                    		{
                    			//创建请求对象
                    			Ext.Ajax.request
                                (
                                    {
                                    	url: Common.MakeAbsoluteUrl('Delete'),
                                    	method: HttpMethod.Post,
                                    	params: selection.data,
                                    	callback: function (options, success, response)
                                    	{
                                    		//处理错误
                                    		if (Common.HandleError(options, success, response))
                                    		{
                                    			//刷新数据
                                    			store.load();
                                    		}
                                    	}
                                    }
                                );
                    		}
                    	}
                    }
                );
    		}
    	},

    	//处理刷新按钮点击事件
    	onRefreshClick: function ()
    	{
    		//刷新数据
    		this.store.load();
    	},

    	//处理新增按钮点击事件
    	onAddClick: function ()
    	{
    		//判定窗体是否创建
    		if (!this.win_create)
    		{
    			//获得数据存储对象
    			var store = this.store;

    			//创建窗体
    			this.win_create = new Ext.Window
                (
                    {
                    	title: '新增条目',
                    	maximizable: false,
                    	maximized: false,
                    	width: 360,
                    	height: 240,
                    	bodyBorder: false,
                    	draggable: true,
                    	isTopContainer: true,
                    	modal: true,
                    	resizable: false,
                    	bodyPadding: 0,
                    	closeAction: 'hide',
                    	closable: false,
                    	layout: 'fit',
                    	fieldDefaults:
                        {
                        	labelAlign: 'left',
                        	labelWidth: 72,
                        	anchor: '100%'
                        },
                    	items:
                        [
                            {
                            	xtype: 'form',
                            	method: 'POST',
                            	waitMsgTarget: true,
                            	waitTitle: Common.ApplicationName,
                            	frame: false,
                            	bodyPadding: 12,
                            	bodyStyle: 'background-color:White;margin:0;',
                            	bodyBorder: false,
                            	border: 0,
                            	autoScroll: true,
                            	defaultType: 'textfield',
                            	autoScroll: false,
                            	fieldDefaults:
                                {
                                	labelAlign: 'left',
                                	labelWidth: 72,
                                	anchor: '100%',
                                	msgTarget: 'qtip',
                                	autoFitErrors: true
                                },
                            	items:
                                [
                                    {
                                    	xtype: 'textfield',
                                    	name: 'ItemName',
                                    	fieldLabel: '条目名称',
                                    	emptyText: '最长40个字符',
                                    	allowBlank: false,
                                    	maxLength: 40,
                                    	listeners:
                                        {
                                        	blur: function ()
                                        	{
                                        		//获得拼音字段
                                        		var txtPinYin = this.up('form').down('#txtPinYin');

                                        		//获得输入的内容
                                        		var source = this.getValue();

                                        		//判断是否有输入内容
                                        		if (source && this.isDirty())
                                        		{
                                        			Common.ConvertToPinYin(source, txtPinYin);
                                        		}
                                        	}
                                        }
                                    },
                                    {
                                    	xtype: 'textfield',
                                    	name: 'ItemPinYin',
                                    	itemId: 'txtPinYin',
                                    	fieldLabel: '速查编号',
                                    	emptyText: '最长40个字符',
                                    	allowBlank: true,
                                    	maxLength: 40
                                    },
                                    {
                                    	xtype: 'textfield',
                                    	name: 'ItemValue',
                                    	itemId: 'txtValue',
                                    	fieldLabel: '附加数据',
                                    	emptyText: '最长80个字符',
                                    	allowBlank: true,
                                    	maxLength: 80
                                    }

                                ],
                            	buttons:
                                [
                                    {
                                    	text: '确定',
                                    	height: 26,
                                    	margin: 3,
                                    	handler: function ()
                                    	{
                                    		//获得表单对象
                                    		var form = this.up('form').getForm();

                                    		//检查数据是否合法
                                    		if (form.isValid())
                                    		{
                                    			//提交数据
                                    			form.submit
                                                (
                                                    {
                                                    	url: Common.MakeAbsoluteUrl('Create'),
                                                    	method: HttpMethod.Post,
                                                    	scope: this.up('window'),
                                                    	params: { DictionayID: current_dictionay_id },
                                                    	submitEmptyText: false,
                                                    	waitTitle: '请稍候',
                                                    	waitMsg: '正在保存数据...',
                                                    	success: function (form, action)
                                                    	{
                                                    		//处理提交错误
                                                    		if (Common.HandleFormError(form, action))
                                                    		{
                                                    			//隐藏窗体
                                                    			this.hide();

                                                    			//重置数据
                                                    			form.reset();

                                                    			//加载数据
                                                    			store.load();
                                                    		}
                                                    	},
                                                    	failure: Common.HandleFormFailure
                                                    }
                                                );
                                    		}
                                    	}
                                    },
                                    {
                                    	text: '取消',
                                    	height: 26,
                                    	margin: 3,
                                    	handler: function ()
                                    	{
                                    		//获得表单对象
                                    		var form = this.up('form').getForm();
                                    		//重置数据
                                    		form.reset();
                                    		//隐藏窗体
                                    		this.up('window').hide();
                                    	}
                                    }
                                ]
                            }
                        ]
                    }
                 );
    		}

    		//显示窗体
    		this.win_create.show();
    	},

    	//处理编辑按钮点击事件
    	onEditClick: function ()
    	{
    		//获得数据存储对象
    		var store = this.store;

    		//获得选中的行
    		var selection = this.getView().getSelectionModel().getSelection()[0];

    		//判断是否选中行
    		if (selection)
    		{
    			//判定窗体是否已经创建
    			if (!this.win_edit)
    			{
    				//创建窗体
    				this.win_edit = new Ext.Window
                    (
                        {
                        	title: '编辑条目',
                        	maximizable: false,
                        	maximized: false,
                        	width: 360,
                        	height: 240,
                        	autoScroll: false,
                        	bodyBorder: false,
                        	draggable: true,
                        	isTopContainer: true,
                        	modal: true,
                        	resizable: false,
                        	bodyPadding: 0,
                        	closeAction: 'hide',
                        	closable: false,
                        	layout: 'fit',
                        	fieldDefaults:
                            {
                            	labelAlign: 'left',
                            	labelWidth: 72,
                            	anchor: '100%'
                            },
                        	listeners:
                            {
                            	//挂接显示事件
                            	show: function (win, options)
                            	{
                            		//查询表单对象对象
                            		var form = win.down('form').getForm();

                            		//加载数据
                            		form.load
                                    (
                                        {
                                        	url: Common.MakeAbsoluteUrl('Details?id=' + win.current_row.ItemID),
                                        	waitMsg: '数据加载中...',
                                        	failure: function (form, action)
                                        	{
                                        		//处理错误
                                        		Common.HandleFormFailure(form, action);

                                        		//隐藏窗体
                                        		win.hide();
                                        	}
                                        }
                                    );
                            	}
                            },
                        	items:
                            [
                                {
                                	xtype: 'form',
                                	method: HttpMethod.POST,
                                	waitMsgTarget: true,
                                	waitTitle: Common.ApplicationName,
                                	frame: false,
                                	bodyPadding: 12,
                                	bodyStyle: 'background-color:White;margin:0;',
                                	bodyBorder: false,
                                	border: 0,
                                	defaultType: 'textfield',
                                	fieldDefaults:
                                    {
                                    	labelAlign: 'left',
                                    	labelWidth: 72,
                                    	anchor: '100%',
                                    	msgTarget: 'qtip',
                                    	autoFitErrors: true
                                    },
                                	reader: Ext.create
                                    (
                                        'Ext.data.reader.Json',
                                        {
                                        	model: 'DictionaryItemListRow',
                                        	record: 'data',
                                        	successProperty: 'success',
                                        	idProperty: 'ItemID',
                                        	messageProperty: 'message'
                                        }
                                    ),
                                	items:
                                    [
                                        {
                                        	xtype: 'textfield',
                                        	name: 'ItemID',
                                        	allowBlank: false,
                                        	hidden: true
                                        },
                                        {
                                        	xtype: 'textfield',
                                        	name: 'DictionayID',
                                        	allowBlank: false,
                                        	hidden: true
                                        },
                                        {
                                        	xtype: 'textfield',
                                        	name: 'ItemName',
                                        	fieldLabel: '条目名称',
                                        	emptyText: '最长40个字符',
                                        	allowBlank: false,
                                        	maxLength: 40,
                                        	listeners:
                                            {
                                            	blur: function ()
                                            	{
                                            		//获得拼音字段
                                            		var txtPinYin = this.up('form').down('#txtPinYin');

                                            		//获得输入的内容
                                            		var source = this.getValue();

                                            		//判断是否有输入内容
                                            		if (source && this.isDirty())
                                            		{
                                            			Common.ConvertToPinYin(source, txtPinYin);
                                            		}
                                            	}
                                            }
                                        },
                                        {
                                        	xtype: 'textfield',
                                        	name: 'ItemPinYin',
                                        	itemId: 'txtPinYin',
                                        	fieldLabel: '速查编号',
                                        	emptyText: '最长40个字符',
                                        	allowBlank: true,
                                        	maxLength: 40
                                        },
                                        {
                                        	xtype: 'textfield',
                                        	name: 'ItemValue',
                                        	itemId: 'txtValue',
                                        	fieldLabel: '附加数据',
                                        	emptyText: '最长80个字符',
                                        	allowBlank: true,
                                        	maxLength: 80
                                        }
                                    ],
                                	buttons:
                                    [
                                        {
                                        	text: '确定',
                                        	height: 26,
                                        	margin: 3,
                                        	handler: function ()
                                        	{
                                        		//获得表单对象
                                        		var form = this.up('form').getForm();

                                        		//检查数据是否合法
                                        		if (form.isValid())
                                        		{
                                        			//提交数据
                                        			form.submit
                                                    (
                                                        {
                                                        	url: Common.MakeAbsoluteUrl('Update'),
                                                        	scope: this.up('window'),
                                                        	submitEmptyText: false,
                                                        	waitTitle: '请稍候',
                                                        	waitMsg: '正在保存数据...',
                                                        	success: function (form, action)
                                                        	{
                                                        		//处理提交错误
                                                        		if (Common.HandleFormError(form, action))
                                                        		{
                                                        			//重置数据
                                                        			form.reset();
                                                        			//隐藏窗体
                                                        			this.hide();
                                                        			//刷新数据
                                                        			store.load();
                                                        		}
                                                        	},
                                                        	failure: Common.HandleFormFailure
                                                        }
                                                    );
                                        		}
                                        	}
                                        },
                                        {
                                        	text: '取消',
                                        	height: 26,
                                        	margin: 3,
                                        	handler: function ()
                                        	{
                                        		//获得表单对象
                                        		var form = this.up('form').getForm();

                                        		//重置数据
                                        		form.reset();

                                        		//隐藏窗体
                                        		this.up('window').hide();
                                        	}
                                        }
                                    ]
                                }
                            ]
                        }
                    );
    			}

    			//设置当前行
    			this.win_edit.current_row = selection.data;

    			//显示窗体
    			this.win_edit.show();
    		}
    	}
    }
);

//挂接环境准备完毕事件
Ext.onReady
(
    function ()
    {
    	//初始化快速提示
    	Ext.QuickTips.init();

    	//设置状态保存提供者（当前设置为Cookie）
    	Ext.state.Manager.setProvider(Ext.create('Ext.state.CookieProvider', { path: _Current_ActionUrl }));

    	//初始化附加验证类型
    	Common.InitAdditionalValidation();

    	//创建计量单位存储
    	if (!store_master_categories)
    	{
    		//创建计量单位存储对象
    		store_master_categories = Ext.create
            (
                'Ext.data.Store',
                {
                	fields: ['ID', 'Name'],
                	data: master_categories
                }
            );
    	}

    	//创建数据存储对象
    	var store = Ext.create
        (
            'Ext.data.Store',
            {
            	pageSize: 20,
            	autoSync: true,
            	autoLoad: false,
            	root: 'data',
            	remoteFilter: true,
            	remoteSort: true,
            	defaultRootProperty: 'data',
            	model: 'DictionaryItemListRow',
            	proxy:
                {
                	type: 'ajax',
                	url: Common.MakeAbsoluteUrl('Select'),
                	batchActions: false,
                	reader:
                    {
                    	type: 'json',
                    	root: 'data'
                    },
                	listeners:
                    {
                    	exception: function (proxy, response, operation, options)
                    	{
                    		//处理错误
                    		Common.HandleProxyError(proxy, response, operation, options);
                    	}
                    }
                }
            }
        );
    	//创建表格
    	var grid = Ext.create
        (
            'DictionayItem.Grid',
            {
            	store: store,
            	stateful: true,
            	stateId: 'dictionayitem-grid-state-grid',
            	height: 600,
            	width: '100%',
            	id: 'dictionayitem-grid',
            	title: '',
            	renderTo: 'data-grid',
            	columnLines: true,
            	viewConfig:
                {
                	stripeRows: true,
                	loadingText: '数据加载中...',
                	singleSelect: true
                },
            	//创建分页工具栏
            	bbar: Ext.create
                (
                    'Ext.PagingToolbar',
                    {
                    	store: store,
                    	displayInfo: true,
                    	displayMsg: '第 {0} - 第 {1} 条记录，共 {2} 条记录',
                    	emptyMsg: ''
                    }
                ),
            	columns:
                [
                    {
                    	text: '条目名称',
                    	width: 240,
                    	sortable: true,
                    	align: 'left',
                    	dataIndex: 'ItemName',
                    	hideable: false
                    },
                    {
                    	text: '速查编号',
                    	width: 160,
                    	sortable: true,
                    	align: 'left',
                    	dataIndex: 'ItemPinYin',
                    	hideable: false
                    },
                    {
                    	text: '附加数据',
                    	minWidth: 160,
                    	flex: true,
                    	sortable: false,
                    	align: 'left',
                    	dataIndex: 'ItemValue',
                    	hideable: false
                    },
                    {
                    	text: '',
                    	flex: true,
                    	sortable: false,
                    	align: 'left',
                    	hideable: false
                    }
                ]
            }
        );

    	//判断是否有数据
    	if (master_categories.length > 0)
    	{
    		//选中第一项
    		grid.down('#dictionayitem_category').select(master_categories[0].ID);
    	}

    	$(window).bind
        (
            "resize",
            function ()
            {
            	//调整表格宽度
            	Common.AdjustGridWidth('dictionayitem-grid', 'body_content');
            }
        );

    	//调整表格宽度
    	Common.AdjustGridWidth('dictionayitem-grid', 'body_content');
    }
);
